import {View, TouchableOpacity, Text, ToastAndroid, StyleSheet, ActivityIndicator} from 'react-native';
import {
  requestPermissions, // 请求设备权限
  connectToDeviceByDeviceId, // 连接设备通过 id
  disconnectDevice, // 断开连接
  updateBikeStatus,
  monitorDisConnect
} from '@/utils/ble';
import {useEffect, useRef, useState} from 'react';
import { Characteristic } from 'react-native-ble-plx';
import { BluetoothCtrlBikeCommandEnum, BluetoothStatusTypeEnum } from '@/constants/BluetoothEnum';
import IconButton from '@/components/IconButton';

// const deviceId:string = 'CA:B9:4A:4B:0A:9F' // 我自己的车辆
const deviceId:string = 'D2:EB:0D:9E:85:59'
let reconnectTimer:any = null
export default function App() {
  const [connecting, setConnecting] = useState<boolean>(false); // 连接状态
  const [unConnetced, setUnConnetced] = useState<boolean>(true); // 断连状态
  const [characteristic, setCharacteristic] = useState<Characteristic>(); // 蓝牙设备特征值
  const statusInfoRef = useRef<{ 
    connectStatus: BluetoothStatusTypeEnum, //连接结果
  }>({ connectStatus: BluetoothStatusTypeEnum.未连接})
  useEffect(() => {
    init()
    onDisconnect()
  }, []);

  async function init() {
    const success = await toRequestPermissions();
    if(success) {
      connectBike()
    }
  }

  async function cancelConnectDevice() {
    await disconnectDevice(deviceId, (flag: boolean) => {
      if(flag) {
        setConnecting(false)
        setCharacteristic(null)
        ToastAndroid.show('操作成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 连接车辆
  function connectBike() {
    if(!deviceId) {
      return
    }
    setConnecting(true)
    // 连接设备
    connectToDeviceByDeviceId(deviceId, (flag: boolean, characteristic: Characteristic) => {
      setConnecting(false)
      if(flag) {
        setCharacteristic(characteristic)
        setUnConnetced(false)
        statusInfoRef.current.connectStatus = BluetoothStatusTypeEnum.已连接 //连接成功
      } else {
        setCharacteristic(null)
        console.log('连接断开0')
        statusInfoRef.current.connectStatus = BluetoothStatusTypeEnum.未连接 //连接失败
      }
    })
  }
  // 监听连接断开
  function onDisconnect() {
    monitorDisConnect(deviceId, (err) => {
      console.log('连接断开1')
      setCharacteristic(null)
      statusInfoRef.current.connectStatus = BluetoothStatusTypeEnum.未连接
      setUnConnetced(true)
      toReconnect()
    })
  }

  // 设置一个计时器定时连接
  function toReconnect() {
    if(reconnectTimer) {
      clearTimeout(reconnectTimer)
    }
    reconnectTimer = setTimeout(() => {
      connectBike()
    }, 10 * 1000)
  }

  // 启动车辆
  function startBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.启动, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('启动成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('启动操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 锁车
  function lockBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.锁车, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('锁车成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('锁车操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 寻找车
  function searchBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.寻车, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('寻车指令发送成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('锁车操作失败!', ToastAndroid.SHORT);
      }
    })
  }

  function toRequestPermissions() {
    return new Promise<boolean>(resolve => {
      requestPermissions((flag: boolean) => {
        console.log('是否获取到了权限', flag);
        if(flag) {
          resolve(flag)
          ToastAndroid.show('蓝牙权限获取成功!', ToastAndroid.CENTER);
        } else {
          resolve(flag)
          ToastAndroid.show('蓝牙权限获取失败!', ToastAndroid.CENTER);
        }
      });
    })
  }
  function getConnectingContent() {
    if(connecting) {
      return <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    }
  }
  function getConnectedContent() {
    if(characteristic) {
      return (
        <View>
          <View style={styles.connectedBox}>
            <Text>已连接设备: {deviceId}</Text>
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='bolt' label='启动' onPress={startBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='https' label='锁车' onPress={lockBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='notifications' label='寻车' onPress={searchBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='cancel' label='断开连接' onPress={cancelConnectDevice} />
          </View>
        </View>
      )
    } else {
      return <Text>连接失败或已断开</Text>
    }
  }
  return (
    <View>
      <Text>自动连接模式</Text>
      {
        getConnectingContent()
      }
      {
        getConnectedContent()
      }
      <View style={styles.btnBox}>
        <IconButton icon='autorenew' label='连接' onPress={connectBike} />
      </View>
    </View>
  );
}


const styles = StyleSheet.create({
  btnBox: {
    marginBottom: 20
  },
  item: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: 50
  },
  itemBorder: {
    borderWidth: 0.2, 
    borderColor: '#CCCCCC'
  },
  connectedBox: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    height: 50
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
})